package com.xuecheng.base.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 勾新杰
 * @version 1.0
 * @description 二维码生成工具
 * @date 2022/10/3 0:03
 */
public class QRCodeUtil {

    /**
     * 生成二维码
     *
     * @param content 二维码对应的URL
     * @param width   二维码图片宽度
     * @param height  二维码图片高度
     * @return Base64 编码的二维码图片字符串
     */
    public static String createQRCode(String content, int width, int height) {
        if (content == null || content.isEmpty())
            throw new IllegalArgumentException("Content cannot be null or empty");
        // 二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 指定字符编码为“utf-8”
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 指定二维码的纠错等级为M
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置图片的边距
        hints.put(EncodeHintType.MARGIN, 1);
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            // zxing生成二维码核心类
            QRCodeWriter writer = new QRCodeWriter();
            // 把输入文本按照指定规则转成二维码
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 生成二维码图片流
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            // 输出流
            ImageIO.write(bufferedImage, "png", os);
            // 原生转码前面没有 data:image/png;base64 这些字段，返回给前端是无法被解析，所以加上前缀
            return "data:image/png;base64," + EncryptUtil.encodeBase64(os.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }
}